/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dailydev.wave.robot.filter;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dailydev.wave.robot.context.IEventContext;

import com.google.wave.api.Event;
import com.google.wave.api.RobotMessageBundle;

/**
 * <p>
 * {@link IFilter} implementation checking if text of blip's document, included
 * within <code>even</code>, matches regular expression. The regular expression
 * is configured using {@link ContentMatch} annotation on a filtered handler
 * method.
 * </p>
 * 
 * @see ContentMatch
 * @author Roman Bosak, DailyDev.org
 */
public class ContentMatchFilter implements IFilter {

    /**
     * 
     */
    public static final String CONTEXT_MATCH_RANGES = "MATCH_RANGES";

    protected Map<String, Pattern> patterns = new HashMap<String, Pattern>();

    /** {@inheritDoc} */
    @Override
    public boolean filter(Method method, RobotMessageBundle bundle, Event event, IEventContext context) {
        ContentMatch annotation = method.getAnnotation(ContentMatch.class);
        if (annotation != null) {
            String patternString = annotation.value();
            Pattern pattern = getPattern(patternString);

            String blipText = event.getBlip().getDocument().getText();
            Matcher matcher = pattern.matcher(blipText);

            List<MatchResult> ranges = new ArrayList<MatchResult>();
            while (matcher.find()) {
                MatchResult matchResult = matcher.toMatchResult();
                ranges.add(matchResult);
            }

            if (ranges.isEmpty()) {
                return false;
            }

            context.put(CONTEXT_MATCH_RANGES, ranges);
        }
        return true;
    }

    /**
     * @param patternString
     * @return
     */
    protected Pattern getPattern(String patternString) {
        Pattern pattern = patterns.get(patternString);
        if (pattern == null) {
            pattern = Pattern.compile(patternString);
            patterns.put(patternString, pattern);
        }
        return pattern;
    }

}
